/**
 * Project Name: jxcommons
 * Package Name: org.jxcommons.io
 * created on 22.11.2012 by jkonopka
 */
package org.jenkon.commons.io.utils;

import java.io.File;

/**
 * util class with helping methods for filename handling.
 * 
 * @author Jens Konopka
 * 
 */
public final class FilenameUtils {

	/**
	 * hide public constructor for this util class.
	 */
	private FilenameUtils() {
	}
	
	/**
	 * @param pathname
	 * @param extension
	 * @return
	 */
	public static boolean endsWith(final File pathname, final String extension) {
		return endsWith(pathname, extension, true);
	}

	/**
	 * @param pathname
	 * @param extension
	 * @param caseSensitive
	 * @return
	 */
	public static boolean endsWith(final File pathname, final String extension, final boolean caseSensitive) {

		if (caseSensitive) {

			if (endsWith(pathname.getName(), extension)) {
				return true;
			}

		} else {

			if (endsWith(pathname.getName().toLowerCase(), extension.toLowerCase())) {
				return true;
			}

		}

		return false;

	}

	/**
	 * @param pathname
	 * @param extension
	 * @return
	 */
	private static boolean endsWith(final String pathname, final String extension) {
		return pathname.endsWith(extension);
	}

	/**
	 * concat the {@link String} array of paths. include if not exist the correct {@link File#separator}.
	 * 
	 * @param paths {@link String} array with file paths
	 * @return the concated parts of paths
	 */
	public static String concat(final String... paths) {
		final StringBuilder sb = new StringBuilder();
		for (final String path : paths) {
			sb.append(path);
			if (!sb.toString().endsWith(File.separator)) {
				sb.append(File.separator);
			}
		}
		sb.delete(sb.lastIndexOf(File.separator), sb.length());
		return sb.toString();
	}

	/**
	 * <p>
	 * Get the extension of a file.
	 * </p>
	 * 
	 * <p>
	 * Get the extension of a file. If the file has no extension, then return <code>null</code>.<br>
	 * Return the extension with no dot.
	 * </p>
	 * 
	 * @param file {@link File} from get the extension
	 * @return the extension or <code>null</code>
	 * @throws NullPointerException if {@link File} <code>== null</code>
	 * @see #getExtension(String)
	 */
	public static String getExtension(final File file) {
		return getExtension(file.getAbsolutePath());
	}

	/**
	 * <p>
	 * Get the extension of a file.
	 * </p>
	 * 
	 * <p>
	 * Get the extension of a file. If the file has no extension, then return <code>null</code>.<br>
	 * Return the extension with no dot.
	 * </p>
	 * 
	 * @param file filename from get the extension
	 * @return the extension or <code>null</code>
	 * @throws NullPointerException if parameter <code>== null</code>
	 */
	public static String getExtension(final String file) {
		if (!file.contains(".")) {
			return null;
		}
		return file.substring(file.lastIndexOf(".") + 1, file.length());
	}

}
